//
//  XCWaterFallLayout.m
//  collectViewDemo
//
//  Created by wulanzhou on 2016/11/4.
//  Copyright © 2016年 wulanzhou. All rights reserved.
//

#import "XCWaterFallLayout.h"

@implementation XCWaterFallLayout

- (instancetype)init{

    if (self=[super init]) {
        
        self.columnsCount = 3;
        self.columnMargin = 10;
        self.rowMargin = 10;
        // 四周的距离设置
        self.sectionInset=UIEdgeInsetsMake(10, 10, 10, 10);
        
        self.scrollDirection = UICollectionViewScrollDirectionVertical;
        
        self.macYDict=[NSMutableDictionary dictionaryWithCapacity:0];
        self.attrsArray=[[NSMutableArray alloc] initWithCapacity:0];
    }
    return self;
}

//这个方法的设定是为了保证只要布局重新计算,我们就刷新layout里面的attributes
- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds{
    
    //NSLog(@"%s",__func__);

    return YES;
}

//每一次重新布局都需要调用这个方法，所以要讲之间存储的item属性和maxY都清空，然后重新计算
- (void)prepareLayout{
    [super prepareLayout];
    
    //NSLog(@"%s",__func__);
    
    
    
    //1.清空最大的Y值,都设置成top
    //self.macYDict[key]
    for (int i=0; i<self.columnsCount; i++) {
        NSString *colum=[NSString stringWithFormat:@"%i",i];
        self.macYDict[colum]=@(self.sectionInset.top);
    }
    
    //2.计算所有cell的属性加到数组中
    [self.attrsArray removeAllObjects];
    
    
    NSInteger numSections = [self.collectionView numberOfSections];
    for(NSInteger section = 0; section < numSections; section++){
        NSInteger numItems = [self.collectionView numberOfItemsInSection:section];
        //添加头
        [self.attrsArray addObject:[self layoutAttributesForSupplementaryViewOfKind:UICollectionElementKindSectionHeader atIndexPath:[NSIndexPath indexPathForItem:0 inSection:section]]];
        
        for(NSInteger item = 0; item < numItems; item++){
            NSIndexPath *indexPath=[NSIndexPath indexPathForRow:item inSection:section];
            UICollectionViewLayoutAttributes *attrs=[self layoutAttributesForItemAtIndexPath:indexPath];
            [self.attrsArray addObject:attrs];
        }
    }
    //end of first section

    /**
    NSInteger count=[self.collectionView numberOfItemsInSection:0];
    for (int i=0; i<count; i++) {
        NSIndexPath *indexPath=[NSIndexPath indexPathForRow:i inSection:0];
        UICollectionViewLayoutAttributes *attrs=[self layoutAttributesForItemAtIndexPath:indexPath];
        [self.attrsArray addObject:attrs];
    }
     
     **/
}

- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath{

    //NSLog(@"%s",__func__);
    
   
    
    //1.寻找出最短的那一列
    __block NSString *minColumn = @"0";
    [self.macYDict enumerateKeysAndObjectsUsingBlock:^(NSString *column, NSNumber *maxY, BOOL * _Nonnull stop) {
        
        if ([maxY floatValue]<[self.macYDict[minColumn] floatValue]) {
            minColumn = column;
        }
    }];
    
    //NSLog(@" minColumn =%@",minColumn);
    
    // 2.计算尺寸
    CGFloat width= (self.collectionView.frame.size.width - self.sectionInset.left - self.sectionInset.right -self.columnMargin * (self.columnsCount - 1))/self.columnsCount;
    
    // 3.高度需要根据宽度乘以图片实际的比例来计算
    CGFloat height = [self.delegate waterFallLayout:self heightForWidth:width atIndexPath:indexPath];
    
    // 4.计算位置
    CGFloat x=self.sectionInset.left + (width + self.columnMargin) * [minColumn intValue];
    
    CGFloat y=[self.macYDict[minColumn] floatValue] + self.rowMargin;
    
    //NSLog(@" y =%f",y);
    
    // 5.更新最大的Y值
    self.macYDict[minColumn] = @(y+height);
    
    UICollectionViewLayoutAttributes *attrs=[UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
    attrs.frame = CGRectMake(x, y, width, height);
    
    
    
    //NSLog(@"index = %d,frame =%@",indexPath.row,NSStringFromCGRect(attrs.frame));
    
    return attrs;
}



- (CGSize)collectionViewContentSize{
    
    //NSLog(@"%s",__func__);
    
    /****/
    //假设现在Y最大的是第0列
    __block NSString *maxColumn = @"0";
    //对这个maxYDict 进行枚举，选出最长的那一行
    [self.macYDict enumerateKeysAndObjectsUsingBlock:^(NSString *column, NSNumber *maxY, BOOL * _Nonnull stop) {
        if ([maxY floatValue]>[self.macYDict[maxColumn] floatValue]) {
            maxColumn = column;
        }
    }];
    
    //计算出最大的Y值
    return CGSizeMake(0, [self.macYDict[maxColumn] floatValue] + self.sectionInset.bottom);
    
}

- (nullable NSArray<__kindof UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect{

    //NSLog(@"%s",__func__);
    return self.attrsArray;
}

- (UICollectionViewLayoutAttributes *)layoutAttributesForDecorationViewOfKind:(NSString *)elementKind atIndexPath:(NSIndexPath *)indexPath {
    
    NSLog(@"layoutAttributesForDecorationViewOfKind section =%d ,row =%d",indexPath.section,indexPath.row);
    
    UICollectionViewLayoutAttributes *attributes = [UICollectionViewLayoutAttributes layoutAttributesForDecorationViewOfKind:elementKind withIndexPath:indexPath];
    attributes.size = CGSizeMake(55, 55);
    //attributes.center = CGPointMake(0, 0);
    //attributes.zIndex = 1;
    return attributes;
}
@end
